import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-10-02
 * Time: 15:32
 */

class TreeNode2 {
    int val;
    TreeNode2 left;
    TreeNode2 right;
    TreeNode2() {}
    TreeNode2(int val) { this.val = val; }
    TreeNode2(int val, TreeNode2 left, TreeNode2 right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Main2 {
    public List<Integer> postorderTraversal(TreeNode2 root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode2> stack=new Stack<>();
        if(root==null){
            return list;
        }

        TreeNode2 prev=null;

        TreeNode2 cur=root;
        while(cur!=null||!stack.isEmpty()){

            while(cur!=null){
                stack.add(cur);
                cur=cur.left;
            }
            TreeNode2 top=stack.peek();
            //关键点在于已经遍历过的怎样防止再次遍历
            //如果这个节点得右树已经遍历过了即
            // prev==top.right直接将这个节点也add之后pop
                               //    🔺🔺🔺
            if(top.right==null||prev==top.right){

                stack.pop();
                list.add(top.val);
                //🔺🔺🔺
                prev=top;
            }else{
                //如果右子树为空就不用再让cur变化了
                //非常关键🔺🔺🔺
                cur=top.right;
            }
        }
        return list;
    }
}
